/**
 * @author GhostWei
 */
var col = document.getElementsByTagName("script");
var jsrc = col.item(col.length-1).src; 
var i = jsrc.indexOf("?"); 
var params = jsrc.substr(i + 1, jsrc.length).replace('&amp;', '&').split('&');

var photo = {
	SWFUpload: null,
	preview_url: null,
	box: null,
	_next: null,
	_previous: null,
	_save: null,
	_saveValue: 'Save',
	_cover: null,
	_coverValue: 'Set As Cover',
	mask: null,
	preview: null,
	body: null,
	special_id: 0,
	sid: null,
	url: null,
	
	showLine: function(id) {
		this.mask.css({'background-image': 'none'});
		this.mask.show();
		this.box.show();
		this.resize();
		var data = this.formParams(false, true);
		data.push('saveShow=1');
		var _data = 'sid=' + this.sid + '&id=' + id + '&special_id=' + this.special_id + '&r='
				+ Math.random().toString() + '&' + data.join('&');
		var self = this;
		$.ajax({type:'POST',dataType:'json',url:this.url,data:_data,success:function(json, status){
			try {
				if(json.status == 0) {
					throw json;
				}
				if(json.next) {
					self._next.click(function(){return self.showLine(json.next);}).removeAttr('disabled');
				}
				if(json.previous) {
					self._previous.click(function(){return self.showLine(json.previous);}).removeAttr('disabled');
				}
				if(self._cover) {
					self._cover.click(function(){self.setCover();return false;}).removeAttr('disabled');
				}
				self._save.removeAttr('disabled').click(function(){
					self.save();
					return false;
				});
				self.mask.css({'background-image':'url(' + photo.preview_url + json.hash + '/large)'});
				self.body.html(json.formHtml);
				self.preview = self.box.find('span.preview').eq(0);
				swfSetting.post_params = {'type': 'image', 'special_id': self.special_id, 'id': id, 'sid': self.sid, 'swfupload': '1'};
				swfSetting.upload_url = self.url;
				self.SWFUpload = new SWFUpload(swfSetting);
				self.resize();
			} catch (e) {
				_error(e.message);
			}
		}, beforeSend: function(req) {
			self.body.html('<p>LOADING.........</p>');
			self._next.unbind('click').attr('disabled', 'disabled').click(function(){return false;});
			self._previous.unbind('click').attr('disabled', 'disabled').click(function(){return false;});
			if(self._cover) {
				self._cover.unbind('click').attr('disabled', 'disabled').click(function(){return false;});
			}
			self._save.unbind('click').attr('disabled', 'disabled');
		}, error: function (req, status, e) {
			if(req['status'] == 200) {
				self.body.html(req['responseText']);
				self.resize();
			} else {
				_error(req['responseText']);
			}
		},timeout: 30000});
		return false;
		
		function _error(msg) {
			var s = '';
			s += '<div class="msg">';
			s += '<div class="common error" style="border:0;background:#fff;">';
			s += '<i class="icon"></i>';
			s += '<h4>' + msg + '</h4>';
			s += '</div></div>';
			self.body.html(s);
			self.resize();
		}
	},
	
	setCover: function() {
		var self = this;
		var data = this.formParams(false, false);
		data.push('setCover=1');
		$.ajax({type:'POST',dataType:'json',url:this.url,data:data.join('&'),success:function(json, status){
			try {
				if(json.status == 0) {
					throw json;
				}
			} catch (e) {
				_error(e.message);
			}
			self._save.removeAttr('disabled').html(self._saveValue);
			self._cover.removeAttr('disabled').html(self._coverValue);
		}, beforeSend: function(req) {
			self._save.attr('disabled', 'disabled').html(self._saveValue);;
			self._cover.attr('disabled', 'disabled').html('SEND..');
		}, error: function (req, status, e) {
			if(req['status'] == 200) {
				_error(req['responseText']);
			} else {
				_error(req['responseText']);
			}
		},timeout: 30000});
		
		function _error(msg) {
			self._save.removeAttr('disabled').html(self._saveValue);
			self._cover.removeAttr('disabled').html(self._coverValue);
			alert('Error:\n' + msg);
		}
	},
	
	save: function() {
		var data = this.formParams(true, false);
		var self = this;
		$.ajax({type:'POST',dataType:'json',url:this.url,data:data.join('&'),success:function(json, status){
			try {
				if(json.status == 0) {
					throw json;
				}
			} catch (e) {
				_error(e.message);
			}
			self._save.removeAttr('disabled').html(self._saveValue);
			if(self._cover) {
				self._cover.removeAttr('disabled').html(self._coverValue);
			}
		}, beforeSend: function(req) {
			self._save.attr('disabled', 'disabled');
			if(self._cover) {
				self._cover.attr('disabled', 'disabled').html(self._coverValue);
			}
			self._save.html('SENDING..');
		}, error: function (req, status, e) {
			if(req['status'] == 200) {
				_error(req['responseText']);
			} else {
				_error(req['responseText']);
			}
		},timeout: 30000});
		
		function _error(msg) {
			self._save.removeAttr('disabled');
			self._save.html(self._saveValue);
			if(self._cover) {
				self._cover.removeAttr('disabled').html(self._coverValue);
			}
			alert('Error:\n' + msg);
		}
	},
	formParams: function(sbm, showItem) {
		var serializeData = $('form#ajaxForm').serializeArray();
		var data = [];
		for(var i in serializeData) {
			var e = serializeData[i];
			if(!sbm && e['name'] == 'submit') continue;
			if(showItem && (e['name'] == 'sid' || e['name'] == 'special_id')) continue;
			if(showItem && e['name'] == 'id') {
				e['name'] = 'save_' + e['name'];
			}
			data.push(e['name'] + '=' + encodeURIComponent(e['value']));
		}
		return data;
	},
	
	closeLine: function() {
		this.mask.css({'background-image': 'none'});
		this.mask.hide();
		this.box.hide();
		return false;
	},
	
	resize: function() {
		var w = this.box.width();
		var h = this.box.height();
		var t = -(h / 2) - 30;
		this.box.css({'margin-left': (-w / 2).toString() + 'px', 'margin-top': t.toString() + 'px'});
		var h1 = - $(window).height() / 2;
		if(Math.abs(t) > Math.abs(h1)) {
			this.box.css({'margin-top': h1 + 'px'});
		}
	},
	
	init: function() {
		for(var k = 0; k < params.length; k++) {
			var key = params[k].substring(0, parseInt(params[k].indexOf('=')));
			var val = params[k].substring(parseInt(params[k].indexOf('=') + 1));
			if(key.toLowerCase() == 'special_id') {
				this.special_id = parseInt(val);
			} else if(key.toLowerCase() == 'url') {
				this.url = val;
			} else if(key.toLowerCase() == 'sid') {
				this.sid = val;
			}
		}
		this.box = $('#photoLineBox');
		this._previous = this.box.find('a.previous').eq(0).click(function(){return false;});
		this._next = this.box.find('a.next').eq(0).click(function(){return false;});
		this._save = $('button#ajaxSubmit');
		this._saveValue = this._save.html();
		this._cover = $('button#setCover');
		if(this._cover) this._coverValue = this._cover.html();
		this.mask = $('.mask');
		this.body = $('#boxBody');
		$('table.photo a.img').click(function(){
			var link = $(this).attr('href');
			var id = link.substring(link.lastIndexOf('/') + 1);
			return photo.showLine(id);
		});;
	}
};
var swfSetting = {
	file_post_name: 'file',
	flash_url: 'swfupload.swf',
	upload_url: 'upload',
	post_params: {},
	file_size_limit : "8 MB",
	file_types : "*",
	file_types_description : "Web Image Files",
	file_upload_limit : 0,
	file_queue_limit : 0,
	custom_settings : {},
	http_success : [201, 202],
	debug: false,
	// button_image_url: "images/TestImageNoText_65x29.png",
	button_width: "200",
	button_height: "20",
	button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES,
	button_placeholder_id: "swfUploadPlaceHolder",
	button_text: '<span class="theFont">CLICK HERE TO SELECT IMAGES ..</span>',
	button_text_style: ".theFont{font-size:12px;text-decoration:underline;color:#0000FF;}",
	button_cursor: SWFUpload.CURSOR.HAND,
	button_text_left_padding: 0,
	button_text_top_padding: 5,
	swfupload_loaded_handler: function() {},
	file_dialog_complete_handler: function(numFilesSelected, numFilesQueued, totalNumOfFile) {
		if(numFilesSelected > 1) {
			alert('Please select one file');
			return;
		}
		photo.SWFUpload.startUpload();
	},
	file_queued_handler: function(file) {},
	file_queue_error_handler: function(file, code, msg) {
		$('#swfUploadProcessingHolder').html('<em class="red">' + msg + '</em>').show();
	},
	queue_complete_handler: function(numFilesUploaded) {},
	upload_start_handler: function(file) {
		$('#swfUploadProcessingHolder').html('<em class="green">STARTING UPLOAD...</em>').show();
	},
	upload_progress_handler: function(file, bytes, total) {
		var s = '';
		var percent = (bytes / total) * 100;
		if(percent >= 100) {
			s += '<em class="green">PROCESSING...</em>';
		} else {
			s += 'UPLOADING...(<em class="red">' + percent + '%</em>)';
		}
		$('#swfUploadProcessingHolder').html(s).show();
	},
	upload_error_handler: function(file, code, msg) {
		$('#swfUploadProcessingHolder').html('<em class="red">' + msg + '</em>').show();
	},
	upload_success_handler : function(file, data, response) {
		try {
			var json = JSON.parse(data);
			if(json.status == false || json.status == 0) {
				throw json.message;
			}
			if(typeof(json.file) != 'undefined' && typeof(json.file.hash) != 'undefined') {
				photo.preview.html('<a target="_blank" href="' + photo.preview_url + json.file.hash + '/large"><img src="' + photo.preview_url + json.file.hash + '/thumb"></a>');
			}
		} catch (e) {
			var msg = typeof(e) == 'string' ? e : e.message;
			alert(msg);
		}
		$('#swfUploadProcessingHolder').hide();
	}
};
$(document).ready(function(){
	photo.init();
	$(window).resize();
});
$(window).resize(function(){
	setTimeout(function(){
		var ww = $(window).width(), dw = $(document).width();
		var sw = dw > ww ? ww : dw;
		if(sw < 960) return;
		var w = (sw - 80) / 8;
		var h = w * 0.625;
		$('table.photo a.img').css({'width':  w + 'px', 'height': h + 'px'});
		$('table.photo a.img span').css({'width':  w + 'px', 'height': h + 'px'});
		$('table.photo a.img img').css({'max-width': w + 'px'});
	}, 100);
});
